package com.hula.onion.book.server.spider.platforms.youliwang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("youLiWangSpider")
public class YouLiWangSpider extends SpiderCommon {
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.yooli.com/secure/ssoLogin.action";
    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.yooli.com/userAccount.session.action";

    @Autowired
    private YouLiWangSpiderHelper youLiWangSpiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {
        //1.2 模拟登陆
        String responseStr = HttpUtils.post(LOGIN_URL,
                youLiWangSpiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if (StringUtils.isEmpty(responseStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        logger.info("[YouLiWangSpider] Http response result:{}", responseStr.toString());
        JSONArray jsonArray = JSON.parseArray(responseStr);
        if ("0".equals(jsonArray.getString(0))) {
            //2.1 爬取用户详细信息

            String result = HttpUtils.get(GET_ACCOUNT_INFO_URL, getHttpContext());
            logger.info("[YouLiWangSpider] Http response account result:{}", result);
            //2.2 解析JSON
            return youLiWangSpiderHelper.parseAccountBalance(result);

        } else if ("-4".equals(jsonArray.getString(0))) {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }
}
